package pct.group;

import java.util.Collection;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import pct.database.PcServiceImpl;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

public class HandleGroupApplication extends ActionSupport implements
		Preparable, SessionAware {
	private boolean result;
	private String groupname;
	private String groupDescription;
	private PcServiceImpl pcService = new PcServiceImpl();
	private Map<String, Object> session;

	public String execute() {

		ApplyMessage msg = new ApplyMessage();
		msg.setGroupname(groupname);
		msg.setGroupDescription(groupDescription);

		boolean duplicated = pcService.groupExists(msg);
		if (result == true && !duplicated) {
			pcService.acceptGroupApplication(msg);
		} else {
			pcService.rejectGroupApplication(msg);
		}

		Collection<ApplyMessage> applyList = (Collection<ApplyMessage>) session
				.get("applyMsg");

		boolean changed = true;
		while (changed) {
			for (ApplyMessage i : applyList) {
				if (i.getGroupname().equals(groupname)) {
					applyList.remove(i);
					continue;
				}
			}
			changed = false;
		}

		return SUCCESS;
	}

	public boolean isResult() {
		return result;
	}

	public void setResult(boolean result) {
		this.result = result;
	}

	public String getGroupname() {
		return groupname;
	}

	public void setGroupname(String groupname) {
		this.groupname = groupname;
	}

	public String getGroupDescription() {
		return groupDescription;
	}

	public void setGroupDescription(String groupDescription) {
		this.groupDescription = groupDescription;
	}

	@Override
	public void prepare() throws Exception {
		pcService.connectDB();
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

}
